import util from "./lib/util";

function swapArr(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
}

window.Manage = {
    ShowData() {
        let _this = this;
        this.action = 'data_list';
        document.getElementById('data-list').innerHTML = '';
        util.require(['QList'], function () {
            QList.init({ target: '#data-list', table: _this.table, mode: _this.mode });
        })
    },
    clickBlock(block) {
        let _this = this;
        this.action = 'data_list';
        document.getElementById('data-list').innerHTML = '';
        util.require(['QList'], function () {
            QList.init({ target: '#data-list', table: block.table_name, mode: block.mode });
        })
    },
    SaveConfig() {
        this.save();
    },
    filter_table: '',
    action: 'block',
    field: '',
    mode: 'admin',
    modes: [],
    switchMode(mode) {
        if (mode == this.mode) {
            return
        }
        this.mode = mode;
        this.load(this.table);
    },
    
    customizeMode() {
        const newMode = prompt("请输入新的模式:", this.mode); 
      
        if (newMode !== null && newMode.trim() !== "") {
            console.log("New mode:", newMode);
            this.mode = newMode.trim(); 
            this.tableRow.mode = newMode.trim(); 
        }
    },
    fields: [],
    tables: [],
    table: '',
    tableRow: {},
    default_row: {
        'id': '',
        'can_create': 1,
        'auth':1,
        'table_name': '',
        'list_fields': [],
        'edit_fields': [],
        'search_fields': [],
        'require_fields': [],
        'field_options': {},
        'mini_fields': []
    },
    edit_types: {},
    option_types: {},
    filter_types: {},
    access_key: '',
    lock_sort: false,
    blocks: [],
    load_blocks() {
        let _this = this;
        util.ajax('?act=blocks', {}, (res) => {
            _this.blocks = res.data;
        })
    },
    init() {
        this.edit_types = QEDITOR__CONF.EDIT_TYPES;
        this.option_types = QEDITOR__CONF.OPTION_TYPES;
        this.filter_types = QEDITOR__CONF.FILTER_TYPES;
        this.load_blocks();
    },
    sort(field, sorted_index, target, fields) {
        var arr = [];
        $('li', target).each(function () {
            arr.push($(this).data('field'));
        })
        util.ajax('?act=sort', { table: this.table, mode: this.mode, type: fields, fields: arr })
    },
    getRow(table) {
        this.table = table;
        let _this = this;
        util.ajax('?act=data', { table: table, mode: this.mode }, (res) => {
            if (res.data && typeof res.data.id != "undefined") {
                _this.tableRow = res.data;
            } else {
                _this.tableRow = _this.default_row;
                _this.tableRow.table_name = table;
            }
            _this.field_option('type');
            _this.field_option('option_callback');
            _this.field_option('option_value');
            _this.field_option('placeholder');
            _this.field_option('filter');
            _this.field_option('verify');
            _this.field_option('default_value');
            _this.field_option('condition');
        })
    },
    load(table) {
        this.table = table;
        this.action = 'list_fields';
        let _this = this;
        util.ajax('?act=fields', { table: table }, (res) => {
            if (res.code) {
                _this.fields = res.data.fields;
                _this.modes = res.data.modes;
            }
            _this.getRow(table);
        })
    },
    field_option(_type_) {

        var field_options = util.cloneObj(this.tableRow.field_options);


        for (var field in this.fields) {

            if (typeof field_options[field] == "undefined" || !field_options[field]) {
                field_options[field] = {}
            }

            if (typeof field_options[field][_type_] == "undefined") {
                field_options[field][_type_] = '';
            }

        }

        this.tableRow.field_options = field_options;

    },
    select(e, r) {
        // console.log(e,JSON.stringify(this.tableRow.field_option));

        var selects = $('select').serializeArray();

        for (var i in selects) {
            var arr = selects[i]['name'].split('.');
            this.tableRow.field_options[arr[1]][arr[2]] = selects[i].value;
        }


    },

    changeOption(field, type, e) {
        this.tableRow.field_options[field][type] = e.target.value;

    },
    showValue(field, type, e) {

        if (typeof this.tableRow['field_options'] == "undefined" || typeof this.tableRow['field_options'][field] == "undefined") {
            return;
        }

        return (typeof this.tableRow['field_options'][field] != "undefined" && typeof this.tableRow['field_options'][field][type] != "undefined")
            ? this.tableRow['field_options'][field][type] : '';
    },
    check(field, type, e) { 
        var in_arr = this.tableRow[type] && this.tableRow[type].indexOf(e.target.value) > -1;
        if (e.target.checked && !in_arr) {
            if (!this.tableRow[type]) {
                this.tableRow[type] = [];
            }
            this.tableRow[type].push(e.target.value);
        } else if (!e.target.checked && in_arr) {
            var index = this.tableRow[type].indexOf(e.target.value);
            this.tableRow[type] = util.removeItem(this.tableRow[type], e.target.value)
        } 

    },
    isCheck(type, field) {
        var checked = this.tableRow[type] && this.tableRow[type].indexOf(field) > -1 ? 'checked' : '';
        return checked;
    },
    optionCheck(field, option_type, type) {

        if (typeof this.tableRow['field_options'] == "undefined" || typeof this.tableRow['field_options'][field] == "undefined") {
            return;
        }

        return this.tableRow['field_options'][field][option_type] && this.tableRow['field_options'][field][option_type] == type ? 'selected' : '';
    },
    save() {
        util.ajax('?act=save', this.tableRow)
    },
    JSONEditor: '',
    // 初始化JSONEditor
    initJsonEditor() {
        // 如果JSONEditor已经存在,则不再重新初始化
        if (this.JSONEditor) {
            // 如果blockData.content存在,则更新现有编辑器的内容
            if (this.blockData.content) {
                this.JSONEditor.set(JSON.parse(this.blockData.content));
            }
            return;
        }

        const container = document.getElementById("jsoneditor");
        const options = {
            mode: 'code',
            modes: ['tree', 'view', 'form', 'code', 'text']
        };
        this.JSONEditor = new JSONEditor(container, options);
        
        // 如果blockData.content存在,则加载现有数据
        if (this.blockData.content) {
            this.JSONEditor.set(JSON.parse(this.blockData.content));
        }
    },
    openSaveBlockModal() {
        this.blockData.table_name=this.table;
        this.blockData.mode=this.mode;
        UIkit.modal('#save-block-modal').show();
        this.initJsonEditor();
    },
    saveToBlock() {
        let _this = this;
        this.blockData.content = JSON.stringify(this.JSONEditor.get()); 
        util.ajax('?act=save_block', this.blockData, (res) => {
            // 关闭模态框
            UIkit.modal('#save-block-modal').hide(); 
            _this.load_blocks();
        })
    },
    // 在data中添加
    blockData: {
        id: '',
        title: '',
        type:'count',
        bg_color: '#efefef',
        text_color: '#333',
        content: '',
        table_name:''
    }
}
